<template>
  <div id="tv_chart_container"></div>
</template>

<script>
export default {
  data() {
    return {
      chart: null,
      currencyName: "ethusdt", //商品名
      currency: "ETH/USDT",
      interval: "1s",
      priceDigitNumber: 2, // price保留的小数位数
      config: [], //各种币的详情（仅用于初始化）
      timer2: 0, //存储计时器的变量
      bars: [],
    };
  },
  mounted() {
    this.initOnReady();
  },
  methods: {
    //初始化
    initOnReady() {
      this.feed = this.createFeed();
      var this_vue = this;
      var widget = (window.tvWidget = new TradingView.widget({
        // fullscreen: true, //是否全屏
        symbol: "AAPL", //商品类型
        interval: this_vue.interval, // k线的时间周期   1-60s 秒  1-60 分钟  xD 天  xW周  xM月     ！！！！！！小时 和 年 必须用 分钟 和 月来设置
        container_id: "tv_chart_container", // 容器id
        datafeed: this_vue.feed, //数据来演
        // datafeed:  new Datafeeds.UDFCompatibleDatafeed("https://demo_feed.tradingview.com"),
        library_path: "charting_library/", // 自带图标库  static文件夹的路径
        // timeframe: "1M", // k线进入页面初始化时 k线显示时间范围  这里是显示  2个月   天数  xD 表示
        preset: "mobile", // 去除左侧工具栏
        timezone: "Asia/Shanghai", //初始化时时间
        debug: false, //可使图表将详细的API日志写入控制台    !!!!!上线时     改为false 影响性能
        locale: "zh", //
        // width:"100%",    fullscreen  为 true 是   宽高生效
        // height:"200px",
        // autosize:true,    //自动调整宽度
        symbol_search_request_delay: 3000, //延迟阈值（以毫秒为单位），用于在用户在搜索框中键入商品名称时减少商品搜索请求的数量
        toolbar_bg: "#fff", // 设置工具栏背景颜色
        customFormatters: {
          dateFormatter: {
            format: function(date) {
              return (
                date.getUTCFullYear() +
                "/" +
                (date.getUTCMonth() + 1) +
                "/" +
                date.getUTCDate()
              );
            },
          },
        }, // 更改 选中k线的时间方法 时间显示方法
        // k线
        overrides: {
          "mainSeriesProperties.candleStyle.upColor": "#e81d5a", // k线上升背景颜色
          "mainSeriesProperties.candleStyle.downColor": "#03a478", // k线下降背景颜色
          // "mainSeriesProperties.candleStyle.drawWick": true,
          // "mainSeriesProperties.candleStyle.drawBorder": true,
          // "mainSeriesProperties.candleStyle.borderColor": "#378658",
          "mainSeriesProperties.candleStyle.borderUpColor": "#e81d5a", // k线上升边框颜色
          "mainSeriesProperties.candleStyle.borderDownColor": "#03a478", // k线下降边框颜色
          "mainSeriesProperties.candleStyle.wickUpColor": "#e81d5a", // 涨    k最高价和最低价
          "mainSeriesProperties.candleStyle.wickDownColor": "#03a478", // 跌   k最高价和最低价
          // "mainSeriesProperties.candleStyle.barColorsOnPrevClose": false
          "paneProperties.legendProperties.showLegend": false,
        },
        // 指标
        studies_overrides: {
          //   "volume.options.showStudyArguments": false,
          //   "volume.options.showLastValue": false,
          //   "volume.volume ma.linewidth": 10,
          // "volume.volume.color.0": "#00FFFF", //下降
          // "volume.volume.color.1": "#0000FF", //上升
          // "volume.volume.transparency": 70,
          // "volume.volume ma.color": "#FF0000",
          // "volume.volume ma.transparency": 30,
          // "volume.volume ma.linewidth": 5,
          // "volume.show ma": true,
          // "bollinger bands.median.color": "yellow",
          // "bollinger bands.upper.linewidth": 7
          "volume.options.showStudyArguments": false,
          "volume.options.showLastValue": false,
          "volume.volume ma.linewidth": 10,
        },
        // disabled_features: ["use_localstorage_for_settings"],
        // enabled_features: ["study_templates"],
        disabled_features: [
          //   "use_localstorage_for_settings",
          //   "legend_context_menu",
          //   "edit_buttons_in_legend",
          //   "adaptive_logo",
          //   "page_context_menu",
          //   "show_chart_property_page",
          //   "timeframes_toolbar",
          //   "go_to_date"
          "volume_force_overlay",
          "use_localstorage_for_settings",
          "header_widget",
          "left_toolbar",
          "legend_context_menu",
          "pane_context_menu",
          "edit_buttons_in_legend",
          "show_logo_on_all_charts",
          "adaptive_logo",
        ], //禁用头部和工具栏
        enabled_features: [
          "move_logo_to_main_pane",
          //  "hide_last_na_study_output",
          //  "dont_show_boolean_study_arguments"
        ], //启动
        // time_frames: [
        //     { text: "50y", resolution: "6M", description: "50 Years" },
        //     { text: "3y", resolution: "W", description: "3 Years", title: "3yr" },
        //     { text: "8m", resolution: "D", description: "8 Month" },
        //     { text: "3d", resolution: "5", description: "3 Days" },
        //     { text: "1000y", resolution: "W", description: "All", title: "All" },
        // ],    //底部出现时间栏
        custom_css_url: "tv.css",
        loading_screen: {
          backgroundColor: "#1d1d27",
          foregroundColor: "#e3c79a",
        },

        charts_storage_url: "http://saveload.tradingview.com",
        charts_storage_api_version: "1.1",
        client_id: "tradingview.com",
        user_id: "public_user_id",
        theme: "Dark", // 修改主题颜色    Dark or  Light
      }));
      // 三条平均线
      tvWidget.onChartReady(function() {
        tvWidget.chart().createStudy("Moving Average", false, false, [5]);
        tvWidget.chart().createStudy("Moving Average", false, false, [10]);
        tvWidget.chart().createStudy("Moving Average", false, false, [20]);
      });
    },
    // 配置数据流
    createFeed() {
      var this_vue = this;
      let myDataFeed = {
        //是图表初始化之后在其中调用callback继续修改配置参数
        onReady: function(callback) {
          callback({
            supports_search: false,
            supports_group_request: false,
            supported_resolutions: [1, 15, 240, "D", "6M"],
            supports_marks: true, //布尔值来标识您的 datafeed 是否支持在K线上显示标记
            supports_timescale_marks: true, //布尔值来标识您的 datafeed 是否支持时间刻度标记。
            exchanges: ["myExchange"],
          });
        },
        //是需要调用onSymbolResolvedCallback方法来设置商品信息
        resolveSymbol: function(
          symbolName, //商品名称
          onSymbolResolvedCallback, //商品信息结构
          onResolveErrorCallback
        ) {
          Promise.resolve().then(() => {
            function adjustScale() {
              let str = "1";
              for (let i = 0; i < this_vue.priceDigitNumber; i++) {
                str += 0;
              }
              return Number(str);
            }
            onSymbolResolvedCallback({
              name: this_vue.currency, //商品名称
              description: this_vue.currency, //描述
              type: "bitcoin", //比特币
              session: "24x7", //交易时间  比特币 24*7
              timezone: "Asia/Shanghai", //交易所时区
              ticker: this_vue.currency, //它是您的商品体系中此商品的唯一标识符 ！！！！一定要指定
              minmov: 1, // 波动
              has_intraday: true, //则由datafeed直接提供的所有周期必须在intraday_multipliers数组中设定。
              intraday_multipliers: ["1"], //It is an array containing intraday resolutions (in minutes) the datafeed wants to build by itself. E.g., if the datafeed reported he supports resolutions ["1", "5", "15"], but in fact it has only 1 minute bars for symbol X, it should set intraday_multipliers of X = [1]. This will make Charting Library to build 5 and 15 resolutions by itself.
              //   has_weekly_and_monthly: false,
              //   has_no_volume: false,
              // udf
              //   regular_session: "24x7",
              pricescale: 10, //刻度
            });
          });
        },
        //主要负责历史数据的加载
        getBars: function(
          symbolInfo,
          resolution,
          from,
          to,
          onHistoryCallback,
          onErrorCallback,
          firstDataRequest
        ) {
          this_vue.getTrade().then((bars) => {
            if (bars.length) {
              onHistoryCallback(bars, { noData: false });
            } else {
              onHistoryCallback(bars, { noData: true });
            }
          });
        },

        //订阅实时数据
        subscribeBars: function(
          symbolInfo,
          resolution,
          onRealtimeCallback,
          subscribeUID,
          onResetCacheNeededCallback
        ) {
          this_vue.timer2 = setInterval(() => {
            this_vue.refresh_1(onRealtimeCallback);
          }, 1000);
        },
        //取消订阅
        unsubscribeBars: function(listenerGUID) {},
      };
      return myDataFeed;
    },

    //获取该币种实时的行情数据
    async getTradeNow() {
      let res = await this.$http.get(
        `http://47.242.25.96:10000/quote/${this.currencyName}.htm?size=600&page=1&_=1625193169674&_version=20210603&_s=aab9dadba171ace713708dafba1d470c`
      );
      return res;
    },

    //实时刷新的函数1
    async refresh_1(onRealtimeCallback) {
      let res = await this.getTradeNow();
      // debugger
      let arr = res.data.split(",");
      let bar = {};
      bar.time = Number(arr[8]);
      bar.close = Number(arr[3]);
      bar.open = Number(arr[3]);
      bar.high = Number(arr[3]);
      bar.low = Number(arr[3]);
      bar.volume = Math.random() * 10;
      if (onRealtimeCallback) {
        onRealtimeCallback(bar);
      } else {
        alert("1");
      }
    },
    //获取该币种之前所有的行情数据
    async getTrade() {
      let interval;
      switch (this.interval) {
        case "1s":
          interval = "1";
          break;
        case "5s":
          interval = "5";
          break;
        case "15s":
          interval = "15";
          break;
        case "30s":
          interval = "30";
          break;
        case "60":
          interval = "60";
          break;
        case "1D":
          interval = "999";
          break;
      }
      let res = await this.$http.get(
        `http://47.242.25.96:10000/kline/${this.currencyName}/${interval}.htm?size=600&page=1&_=1625193169674&_version=20210603&_s=aab9dadba171ace713708dafba1d470c`
      );
      this.bars = res.data.split("|").map((el) => {
        var arr = el.split(",");
        console.log(arr);
        // let date = new Date(this.format(arr[4], "full"));
        // console.log(data);
        return {
          time: arr[4] / 1,
          low: Number(arr[2]),
          high: Number(arr[1]),
          open: Number(arr[0]),
          close: Number(arr[3]),
          volume: Math.random() * 10,
        };
      });
      return this.bars;
    },
    //日期格式化(将202005221747类型的时间的格式化为2020/05/17 17:47)
    format(date, type) {
      let arr1 = []; //年月日
      let arr2 = []; //时分
      let year = date.toString().slice(0, 4);
      let month = date.toString().slice(4, 6);
      let day = date.toString().slice(6, 8);
      let hour = this.interval == "1D" ? "00" : date.toString().slice(8, 10);
      let minutes =
        this.interval == "1D" ? "00" : date.toString().slice(10, 12);
      arr1.push(year); //年
      arr1.push(month); //月
      arr1.push(day); //日
      arr2.push(hour); //时
      arr2.push(minutes); //分
      if (type == "full") {
        return arr1.join("/") + " " + arr2.join(":");
      } else if (type == "nohm") {
        return arr1.join("/");
      } else if (type == "hm") {
        return arr2.join(":");
      }
    },
  },
  beforeDestroy() {
    clearInterval(this.timer2);
  },
};
</script>

<style></style>
